package com.bagus.mediapipefacedetection.utils;

import static android.os.Environment.getExternalStorageDirectory;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.net.Uri;
import android.provider.MediaStore;

import com.bagus.mediapipefacedetection.MainActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {
    /**
     * 旋转Bitmap
     * @param b
     * @param rotateDegree
     * @return
     */
    public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) rotateDegree);
        matrix.postScale(-1, 1);
        Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
        return rotaBitmap;
    }

    public static byte[] getDataFromAssets(Context context, String name) {
        InputStream is = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        AssetManager assets = context.getResources().getAssets();
        try {
            is = assets.open(name);
            byte[] buffer = new byte[2048];
            int count = -1;
            while ((count = is.read(buffer)) > 0) {
                bos.write(buffer, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bos.toByteArray();
    }

    public static byte[] yuv2jpg(byte[] imageData, int width, int height, Rect rect) {
        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            YuvImage yuvImage = new YuvImage(imageData, ImageFormat.NV21, width, height, null);

            yuvImage.compressToJpeg(rect, 100, out);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return out.toByteArray();
    }

    public static Bitmap resizeBitmap(byte[] imageData, int width, int height, Rect rect) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            YuvImage yuvImage = new YuvImage(imageData, ImageFormat.NV21, width, height, null);

            yuvImage.compressToJpeg(rect, 100, out);
            byte[] imageBytes = out.toByteArray();

            Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);

//        bitmap = getReduceBitmap(bitmap, Constant.CROPPED_IMAGE_SIZE);

            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * NV21图像转RGB或BGR
     * @param input NV21格式图像数据
     * @param width 图像宽度
     * @param height 图像高度
     * @param output 输出图像缓冲区
     * @param isRGB 为{@code true}转为RGB图像,否则转为BGR图像
     */
    public static void NV212RGBorBGR(byte[]input , int width , int height , byte[]output,boolean isRGB)
    {
        int nvOff = width * height ;
        int  i, j, yIndex = 0;
        int y, u, v;
        int r, g, b, nvIndex = 0;
        for(i = 0; i < height; i++){
            for(j = 0; j < width; j ++,++yIndex){
                nvIndex = (i / 2)  * width + j - j % 2;
                y = input[yIndex] & 0xff;
                u = input[nvOff + nvIndex ] & 0xff;
                v = input[nvOff + nvIndex + 1] & 0xff;

                // yuv to rgb
                r = y + ((351 * (v-128))>>8);  //r
                g = y - ((179 * (v-128) + 86 * (u-128))>>8); //g
                b = y + ((443 * (u-128))>>8); //b

                r = ((r>255) ?255 :(r<0)?0:r);
                g = ((g>255) ?255 :(g<0)?0:g);
                b = ((b>255) ?255 :(b<0)?0:b);
                if(isRGB){
                    output[yIndex*3 + 0] = (byte) b;
                    output[yIndex*3 + 1] = (byte) g;
                    output[yIndex*3 + 2] = (byte) r;
                }else{
                    output[yIndex*3 + 0] = (byte) r;
                    output[yIndex*3 + 1] = (byte) g;
                    output[yIndex*3 + 2] = (byte) b;

                }
            }
        }
    }

    //保存文件到指定路径
    public static boolean saveImageToGallery(Context context, Bitmap bmp, String fileName) {
        // 首先保存图片
        String storePath = getExternalStorageDirectory().getAbsolutePath() + File.separator + "skin_picture";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File file = new File(appDir, fileName);
        try {
            //file.mkdirs();
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean saveImageToCacheFile(Context context, Bitmap bmp, String fileName) {
        // 首先保存图片
        String storePath = context.getFilesDir() + File.separator + "skin_picture";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File file = new File(appDir, fileName);
        try {
            //file.mkdirs();
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean saveImageToCacheFile2(Context context, Bitmap bmp, String fileName) {
        // 首先保存图片
        File file = new File(fileName);
        try {
            //file.mkdirs();
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     * @param type  0 原图  1 头部图片
     * @return
     */
    public static String getSaveImage(Context context,int type){
        String path = context.getCacheDir() + "/";
        if(type == 0){
            path = path+"full.jpg";
        }else{
            path = path+"head.jpg";
        }
        return path;
    }
}
